local isRecover = false


local sqlfile= "./sqls.txt"
local typefile= "./types.txt"
local statefile= "./state.txt"
local sqls = {}
local types = {}

function saveDataToFile(strings, filename)
    local file = io.open(filename, "w")
    if file then
        for _, str in ipairs(strings) do
            file:write(str, "\n")
        end
        file:close()
        print("Strings saved to " .. filename)
    else
        print("Error opening file for writing.")
    end
end

function readStringsFromFile(filename , isNumber)
    local file = io.open(filename, "r")
    local strings = {}

    if file then
        for line in file:lines() do
            if isNumber then
                table.insert(strings, tonumber(line))
            else
                table.insert(strings, line)
            end
        end
        file:close()
    else
        print("Error opening file for reading.")
    end

    return strings
end



function connect_server()
    proxy.connection.backend_ndx = 1
    local file = io.open(statefile, "r")
    local content = file:read("*a")
    file = io.open(statefile, "w")
    if string.match(content,"^1") then
        print("Start recover...")
        isRecover = true
    end
    if proxy.global.backends[1].state == proxy.BACKEND_STATE_DOWN then
        file:write("1")
        print("Server Down!")
    else
        file:write("0")
    end
    file:close()
end



function read_query(packet)
    local type = packet:byte()
    local sql = packet:sub(2)
    if isRecover then
        sqls=readStringsFromFile(sqlfile,false)
        types=readStringsFromFile(typefile,true)
        local lastid= #sqls
        print("Try to redo the last sql: " ..sqls[lastid])
        local new_query = sqls[lastid]
        proxy.queries:append(1, string.char(types[lastid])  .. new_query)
        proxy.queries:append(2, string.char(type)  .. sql)
        if type == proxy.COM_QUERY then
            table.insert(types,type)
            table.insert(sqls,sql)
            print("Receive SQL: " .. string.sub(packet, 2))
            print("Save SQLs")
            saveDataToFile(sqls,sqlfile)
            saveDataToFile(types,typefile)
        end
        return types[lastid]
    else
        if type == proxy.COM_QUERY then
            table.insert(types,type)
            table.insert(sqls,sql)
            print("Receive SQL: " .. string.sub(packet, 2))
            print("Save SQLs")
            saveDataToFile(sqls,sqlfile)
            saveDataToFile(types,typefile)
        end
    end
end


function read_query_result(inj)
    if isRecover then
        print("Now recover...")
        if inj.id == 2 then
            isRecover=false
            return proxy.PROXY_SEND_RESULT
        else
            return proxy.PROXY_IGNORE_RESULT
        end
    end    
end